package com.biglead.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.biglead.admin.mapper.UmsMenuMapper;
import com.biglead.admin.pojo.UmsMenu;
import com.biglead.admin.pojo.UmsMenuNode;
import com.biglead.admin.service.UmsMenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 后台菜单管理Service实现类
 */
@Service
public class UmsMenuServiceImpl extends ServiceImpl<UmsMenuMapper, UmsMenu> implements UmsMenuService {

    @Override
    public Page<UmsMenu> list(Long parentId, Integer pageSize, Integer pageNum) {
        Page<UmsMenu> page = Page.of(pageNum, pageSize);
        //queryWrapper组装查询where条件
        LambdaQueryWrapper<UmsMenu> queryWrapper = new LambdaQueryWrapper<>();
        //查询条件 ID = 1 的数据
        queryWrapper.eq(UmsMenu::getParentId, parentId);
        //发起查询
        Page<UmsMenu> umsMenuPage = this.page(page, queryWrapper);
        return page;
    }

    @Override
    public UmsMenu getItem(Long id) {
        return this.getById(id);
    }

    @Override
    public boolean update(Long id, UmsMenu umsMenu) {
        UmsMenu byId = this.getById(id);
        if (byId == null) {
            throw new RuntimeException("未查询到菜单");
        }
        return this.updateById(umsMenu);
    }

    @Override
    public boolean delete(Long id) {
        return this.removeById(id);
    }

    @Override
    public boolean create(UmsMenu umsMenu) {
        return this.save(umsMenu);
    }

    @Override
    public List<UmsMenuNode> treeList() {
        //查询所有的菜单
        List<UmsMenu> menuList = this.list();
        //组合
        List<UmsMenuNode> result = menuList.stream()
                .filter(menu -> menu.getParentId().equals(0L))
                .map(menu -> covertMenuNode(menu, menuList))
                .collect(Collectors.toList());
        return result;
    }

    @Override
    public boolean updateHidden(Long id, Integer hidden) {

        UmsMenu byId = this.getById(id);
        if (byId == null) {
            throw new RuntimeException("未查询到菜单");
        }
        byId.setHidden(hidden);
        return this.updateById(byId);
    }

    /**
     * 将UmsMenu转化为UmsMenuNode并设置children属性
     */
    private UmsMenuNode covertMenuNode(UmsMenu menu, List<UmsMenu> menuList) {
        UmsMenuNode node = new UmsMenuNode();
        BeanUtils.copyProperties(menu, node);
        List<UmsMenuNode> children = menuList.stream()
                .filter(subMenu -> subMenu.getParentId().equals(menu.getId()))
                .map(subMenu -> covertMenuNode(subMenu, menuList)).collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }
}
